package com.seveneight.baijiesteward.utils;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.seveneight.baijiesteward.base.Message;
import com.seveneight.baijiesteward.base.MessageBean;
import com.seveneight.baijiesteward.bean.BaseEntity;
import com.seveneight.baijiesteward.http.HttpConfig;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

/**
 * Created by user1 on 2018/2/27.
 */

public class HttpUpload {

    private String path;
    private int type;
    private String userId;
    private String resultcode;
    private int successCode;
    private int failCode;
    private CrossUtil crossUtil;


    public HttpUpload(String userId, int type, String path, int successCode, int failCode) {
        this.path = path;
        this.userId = userId;
        this.type = type;
        this.successCode = successCode;
        this.failCode = failCode;
    }

    public void startUpload() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpClientUtil httpClient = new HttpClientUtil();
                HttpClientUtil.MultipartForm form = httpClient.new MultipartForm();
                //设置form属性、参数
                form.setAction(HttpConfig.BASE_URL + HttpConfig.UPLOAD_IMG);
                File file = new File(path);
                form.addFileField("file", file);
                form.addNormalField("UserID", userId);
                form.addNormalField("ImageBusinessType", type + "");
                resultcode = httpClient.submitForm(form);
                BaseEntity entity = JSONObject.parseObject(resultcode, BaseEntity.class);
                try {
                    if (entity.getRespCode().equals("000000")) {
                        JSONObject jsonObject = JSON.parseObject(entity.getData() + "");
                        String url = jsonObject.getString("ImgUrl");
                        EventBus.getDefault().post(new MessageBean(successCode, url));
                    } else {
                        EventBus.getDefault().post(new MessageBean(failCode, entity.getRespMsg()));
                    }
                } catch (Exception ex) {
                    EventBus.getDefault().post(new MessageBean(failCode, "上传图片失败"));
                }
            }
        }).start();
    }
}
